package com.ruoyi.lvlian.controller;

import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.VehicleInfo;
import com.ruoyi.lvlian.dto.VehicleInfoDto;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.service.IVehicleInfoService;
import com.ruoyi.lvlian.vo.DriverInfoVo;
import com.ruoyi.lvlian.vo.VehicleInfoVo;
import com.ruoyi.lvlian.vo.WarehouseInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Api(value = "车辆信息Controller", tags = "车辆信息Controller")
@RestController
@RequestMapping("/vehicleInfo")
public class VehicleInfoController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(VehicleInfoController.class);

    @Autowired
    private IVehicleInfoService vehicleInfoService;
    @Autowired
    private ICommonService iCommonService;

    @ApiOperation("查询车辆信息列表")
//    //@RequiresPermissions("lvlian:vehicleInfo:list")
    @GetMapping("/list")
    public TableDataInfo list(VehicleInfoDto vehicleInfo) {
        if (Objects.isNull(vehicleInfo.getOrgCodes()) || vehicleInfo.getOrgCodes().isEmpty()) {
            return null;
        }

        if (SecurityUtils.getUserId() == 1) {
            vehicleInfo.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        }

        startPage();
        List<VehicleInfoVo> list = vehicleInfoService.selectVehicleInfoList(vehicleInfo);
        return getDataTable(list);
    }


    @ApiOperation("获取车辆信息详细信息")
//    //@RequiresPermissions("lvlian:vehicleInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(vehicleInfoService.selectVehicleInfoById(id));
    }


    @ApiOperation("获取车辆信息详细信息 可传入id 和车牌号码  getInfoById")
    @GetMapping("/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "获取车辆信息详细信息", required = true) @RequestParam(value = "id") String id) {
        return success(vehicleInfoService.selectVehicleInfoById(id));
    }


    @ApiOperation("新增/修改车辆信息")
//    //@RequiresPermissions("lvlian:vehicleInfo:edit")
    @Log(title = "修改车辆信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated VehicleInfo vehicleInfo) {
        log.info(vehicleInfo.toString());
        if (!"success".equalsIgnoreCase(validateInData(vehicleInfo))) {
            return error(validateInData(vehicleInfo));
        }
        if (StringUtils.isEmpty(vehicleInfo.getDataSource())) {
            vehicleInfo.setDataSource("实时物流小程序");
        }

  /*         VehicleInfo vehicleInfo1 = vehicleInfoService.selectVehicleInfoById(vehicleInfo.getId());
     if(vehicleInfo1 !=null && !vehicleInfo.getPlateNo() .equals(vehicleInfo1.getPlateNo() )){
            return error("车牌号码不能改");
        }*/
        try {
            return toAjax(vehicleInfoService.updateVehicleInfo(vehicleInfo));
        } catch (Exception e) {
            e.printStackTrace();
            return error("保存车辆信息失败");
        }


    }

    private String validateInData(VehicleInfo vehicleInfo) {
        if (StringUtils.isEmpty(vehicleInfo.getPlateNo())) {
            return "车牌号不能为空";
        }
/*        if (StringUtils.isEmpty(vehicleInfo.getDrivingLicenseImg())) {
            return "行驶证正页不能为空";
        }
        if (StringUtils.isEmpty(vehicleInfo.getPlateColor())) {
            return "车牌颜色不能为空";
        }*/
/*        if (StringUtils.isEmpty(vehicleInfo.getLocation())) {
            return "发货地址不能为空";
        }
        if (StringUtils.isEmpty(vehicleInfo.getContactPersonPhone())) {
            return "联系人电话不能为空";
        }*/


        return "success";
    }

/*

    @ApiOperation("根据司机号码查询司机车数量 ")
    @GetMapping("/queryVehicleCountByDriverPhone")
    public AjaxResult queryVehicleCountByDriverPhone(@RequestParam(value = "driverPhone", required = true, defaultValue = "15723122196") String driverPhone) {
        if (StringUtils.isEmpty(driverPhone) && StringUtils.isEmpty(driverPhone)) {
            return error("司机手机号码不能为空");
        }
        if (StringUtils.isNotEmpty(driverPhone) && !PhoneNumberValidator.isValidPhoneNumber(driverPhone)) {
            return error("司机手机号码无效");
        }
        int cnt = vehicleInfoService.queryVehicleCountByDriverPhone(driverPhone);

        return AjaxResult.success(cnt);
    }
*/


    @ApiOperation("根据司机号码,或者驾驶证号码 查询车辆信息列表")
    @GetMapping("/queryVehicleListByDriverPhoneOrId")
    public TableDataInfo queryVehicleListByDriverPhone(@RequestParam(value = "driverPhoneOrId", required = true) String driverPhoneOrId) {
        if (StringUtils.isEmpty(driverPhoneOrId) && StringUtils.isEmpty(driverPhoneOrId)) {
            return getDataTable(null);
        }
        startPage();
//        这里给小程序使用 是要找到有 关联的车

        List<VehicleInfo> list = vehicleInfoService.queryVehicleListByDriverPhoneOrIdEffective(driverPhoneOrId);
        if (list != null && list.size() > 1) {
            list.removeIf(vehicle -> vehicle == null || vehicle.getPlateNo() == null);
        }

/*        VehicleInfo po = list.get(0);
        if (StringUtils.isNotEmpty(po.getDriverLicenseImg())) {
            po.setRealName(true);
        }*/
        return getDataTable(list);
    }


    @PostMapping("/remove")

    @Log(title = "车辆删除", businessType = BusinessType.DELETE)
    public AjaxResult remove(@RequestBody String[] ids) {

        return toAjax(vehicleInfoService.deleteVehicleInfoByIds(ids));
    }


    @ApiOperation("导入车辆")
    @PostMapping("/importInfo")
    @Log(title = "导入车辆", businessType = BusinessType.UPDATE)
    public AjaxResult importInfo(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<VehicleInfo> dtoList = null;
        String msg = "";
        try {
            dtoList = vehicleInfoService.importInfo(file, "车辆信息", 3);
            int totalSussess = vehicleInfoService.bachSave(dtoList);
            int total = dtoList.size();
            int totalFail = total - totalSussess;
            msg = "解析到" + total + "条数据，" + "导入成功" + totalSussess + "条，导入失败" + totalFail + "条！";
        } catch (MysqlDataTruncation e) {
            e.printStackTrace();
            return success("保存数据错误，数据中有异常值");
        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }


        return success(msg);
    }
}
